<template>
  <div class="app-container" style="background-color: #f8f8f8">
    <!--        <div class="div-style">-->
    <el-divider content-position="left"><span class="divider-css">▶患者信息◀</span></el-divider>
    <div class="patient-info-container">
      <el-form ref="formRef" :inline="true" :model="queryParams" label-width="80px">
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="住院号:">
              <el-input ref="hospitalNoInputRef" v-model="queryParams.hospitalNo" clearable
                        placeholder="请输入住院号检索"
                        style="width: 200px"
                        @clear="hospitalNoClear"
                        @keyup.enter="patientSelectClick">
                <template #append>
                  <el-button class="patient-button" type="primary"
                             @click="patientSelectClick">检索
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="患者姓名:">
              <div v-if="queryParams.visitId" style="width: 120px; flex: 1; ">
                                  <span class="fz15 ml5" style="color: #5050e1">
                                    {{
                                      queryParams.name
                                    }}<svg-icon :icon-class="dictStore.getMateDictInfo(
                                      dictDataMap['sys_user_sex'],
                                      queryParams.sex
                                    ).dictValue === '1'
                                      ? 'man'
                                      : 'woman'
                                      " style="margin-left: 10px"/>
                                  </span>
              </div>
              <el-link v-else style="width: 100px;" type="primary" @click="patientSelectClick">请选择患者
              </el-link>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="身份证号:">
                        <span style="width: 100px">{{
                            queryParams.idNo ? queryParams.idNo : "暂无"
                          }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="年龄:">
                            <span v-if="queryParams.visitId" class="fz13" style="width: 150px">{{ queryParams.age }} 岁{{
                                queryParams.ageMonth
                              }} 月{{
                                queryParams.ageDay
                              }}天{{ queryParams.ageHours }}小时
                            </span>
              <span v-else style="width: 150px">暂无</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="联系电话:">
                        <span style="width: 100px">{{
                            queryParams.phone ? queryParams.phone : "暂无"
                          }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="住院次数:">
                       <span>{{
                           queryParams.hospitalizationNumber ? queryParams.hospitalizationNumber : "暂无"
                         }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="入院时间:">
                       <span style="width: 200px">{{
                           queryParams.admissionTime ? queryParams.admissionTime : "暂无"
                         }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="出院时间:">
                       <span>{{
                           queryParams.dischargeTime ? queryParams.dischargeTime : "暂无"
                         }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="住院科室:">
                            <span style="width: 100px">{{
                                queryParams.deptStayedName ? queryParams.deptStayedName : "暂无"
                              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入院诊断:">
                       <span style="width: 160px">{{
                           queryParams.diagnosis ? queryParams.diagnosis : "暂无"
                         }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入院天数:">
                       <span class="ys-css" style="width: 140px">{{
                           queryParams.hospitalizationDays ? queryParams.hospitalizationDays + '天' :
                             "暂无"
                         }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="费别:">
              <el-select v-model="queryParams.chargeType" placeholder="请选择费别" style="width: 200px"
                         @change="chargeTypeChange">
                <el-option v-for="dict in dictDataMap['medical_insurance_type']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="读卡类型:">
              <el-select v-model="queryParams.medicalReadCardType" :disabled="isNotMedical"
                         placeholder="读卡类型"
                         style="width: 120px">
                <el-option v-for="dict in dictDataMap['medical_read_card_type']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
              <el-button :disabled="isNotMedical" type="primary" @click="resetPatient('01301')">
                <svg-icon class="mr5" icon-class="readCard"/>
                读卡
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="结算方式:">
              <el-select v-model="queryParams.psnSetlway" :disabled="isNotMedical" placeholder="结算方式"
                         style="width: 159px">
                <el-option v-for="dict in dictDataMap['psn_setlway']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="业务类型:">
              <el-select v-model="queryParams.ybSerialType" :disabled="isNotMedical" placeholder="读卡类型"
                         style="width: 200px">
                <el-option v-for="dict in dictDataMap['outp_settlement_business_type_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="参保类型:">
              <el-select v-model="queryParams.canBaoType" :disabled="isNotMedical" placeholder="读卡类型"
                         style="width: 200px">
                <el-option v-for="dict in dictDataMap['insurance_type']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label=" ">
              <el-checkbox v-model="queryParams.individualAccount" :disabled="isNotMedical"
                           style="width: 210px">个人账户余额支付
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 遮罩层 -->
      <div v-if="isPreSetl" class="mask-layer patient-mask">
      </div>
    </div>
    <el-divider content-position="left"><span class="divider-css">▶费用信息◀</span></el-divider>
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="fee-info-container">
          <el-divider content-position="center"><span class="divider-css">▶结算列表◀</span></el-divider>
          <el-table ref="clinicOrdersRef" v-adaptive="15" :border="true" :data="inpBillDetailList"
                    :header-cell-style="$headerCellStyle" :stripe="true" :summary-method="getSummaries"
                    highlight-current-row show-summary>
            <el-table-column :align="'center'" label="收据项目" prop="classOnInpName"/>
            <el-table-column :align="'center'" label="应收(元)" prop="costs" width="140">
              <template #default="scope">
                              <span class="ys-css">
                                  {{ parseFloat(scope.row.costs).toFixed(2) }}
                              </span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="实收(元)" prop="charges" width="140">
              <template #default="scope">
                              <span class="ys-css">
                                  {{ parseFloat(scope.row.charges).toFixed(2) }}
                              </span>
              </template>
            </el-table-column>
          </el-table>
          <!-- 遮罩层 -->
          <div v-if="isPreSetl" class="mask-layer fee-mask">
            <div class="mask-content">
              <h1>预结算后不能修改页面操作</h1>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="11">
        <div class="prepayment-container">
          <el-divider content-position="center"><span class="divider-css">▶预交金列表◀</span></el-divider>
          <el-table ref="patPrepaymentRef" v-adaptive="15" :border="true" :data="patPrepaymentList"
                    :header-cell-style="$headerCellStyle"
                    :stripe="true" :summary-method="getPrepaymentSummaries"
                    highlight-current-row show-summary
                    @selection-change="handleSelectionChange">
            <el-table-column :align="'center'" fixed="left" type="selection" width="65"/>
            <el-table-column :align="'center'" label="状态" prop="type" width="80">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['pat_prepayment_type']" :value="scope.row.type"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="收费号" prop="feesNo" width="120px"/>
            <el-table-column :align="'center'" label="支付方式" min-width="140px" prop="payWay">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['pay_way_dict']" :value="scope.row.payWay"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="交款日期" prop="feesNo" width="160">
              <template #default="scope">
                {{ scope.row.createTime }}
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="收款员" prop="createByName" width="140px"/>
            <el-table-column :align="'center'" label="缴费金额(元)" prop="amountOfMoney" width="160px">
              <template #default="scope">
                      <span
                        :class="scope.row.type === '1' ? 'ys-css' : scope.row.type === '2' ? 'refunded-css' : 'cancel-css'">{{
                          parseFloat(scope.row.amountOfMoney).toFixed(2)
                        }}</span>
              </template>
            </el-table-column>
          </el-table>
          <!-- 遮罩层 -->
          <div v-if="isPreSetl" class="mask-layer prepayment-mask">
            <div class="mask-content">
              <h1>预结算后不能修改页面操作</h1>
            </div>
          </div>
        </div>
        <div class="pat-prepayment span-font">
                    <span>
                        共计使用：<span class="ys-css span-font">{{ ids.length }}</span>笔, 总计：<span
                      class="ys-css span-font">{{ prepaymentCosts }}</span> 元
                    </span>
        </div>
      </el-col>
      <el-col :span="7">
        <el-divider content-position="center"><span class="divider-css">▶结算信息◀</span></el-divider>
        <div class="search-container" style="height: calc(100% - 22px)">
          <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
            <el-descriptions-item min-width="200px">
              <template #label>
                <div class="cell-item">
                  <span class="ys-css">合计：</span>
                </div>
              </template>
              <span class="ys-css"> {{ totalPrice }}</span>元
            </el-descriptions-item>
          </el-descriptions>
          <el-row class="mt10">
            支付类型明细
            <el-tooltip class="box-item"
                        content="支付金额中的【-】负数代表退给患者的钱数，正数代表收取患者的钱数" effect="dark"
                        placement="right">
              <i-ep-infoFilled class="infoFilled-style"/>
            </el-tooltip>
            <div class="regist-info-div" style="
                            height: calc(100% - 120px);
                            background-color: #ffffff;
                            position: relative;
                            ">
              <div style="height: 300px; overflow-y: auto">
                <pay-way-list v-if="queryParams.visitId" ref="payWayListRef" :inp-or-outp="inpOrOutp"
                              :total-price="totalPrice" @set-net-receipts="payWayBlur"/>
                <div v-else style="
                    line-height: 105px;
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                  ">
                  暂无数据
                </div>
              </div>
            </div>
          </el-row>
          <div style="margin-top: 10px">
            <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">应收金额:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ totalPrice }} </span>元
              </el-descriptions-item>
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                                        <span class="ys-css">
                                            补&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;缴:
                                        </span>
                  </div>
                </template>
                <span class="ys-css"> {{ retChange }} </span>元
              </el-descriptions-item>
            </el-descriptions>
            <div class="ml5" style="font-size: 14px;color: #bb0202">补缴 = 所有的支付明细相加 -
              应收金额，补缴为【-】负数代表需要给患者退费，
              补缴为正数代表患者需要正常补缴费用，补缴金额为0代表应收金额 = 已缴费用
            </div>
          </div>
          <!--                    <el-button class="ml10" style="position: absolute; bottom: 10px; right: 187px" type="success"-->
          <!--                               @click="chargeOk">-->
          <!--                        <svg-icon class="mr5" icon-class="chargeOk"/>-->
          <!--                        确认收费-->
          <!--                    </el-button>-->
          <el-button v-if="!isNotMedical && !isPreSetl" plain
                     style="position: absolute; bottom: 35px; right: 355px"
                     type="warning" @click="detailUpload">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            费用上传
          </el-button>
          <el-button v-if="!isNotMedical && !isPreSetl" plain
                     style="position: absolute; bottom: 35px; right: 255px"
                     type="danger" @click="detailUploadUndo">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            费用撤销
          </el-button>
          <el-button v-if="!isNotMedical && isPreSetl" plain
                     style="position: absolute; bottom: 35px; right: 255px"
                     type="danger" @click="medicalRegisterUndo">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            取消预结算
          </el-button>
          <el-button v-if="!isNotMedical" plain
                     style="position: absolute; bottom: 35px; right: 140px"
                     type="success" @click="medicalRegister">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            医保预结算
          </el-button>
          <el-button class="ml10" plain style="position: absolute; bottom: 35px; right: 40px" type="primary"
                     @click="chargeOk">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            {{ isNotMedical ? '自费结算' : '医保结算' }}
          </el-button>

        </div>
      </el-col>
    </el-row>
    <!--        </div>-->
    <!-- 待结算患者选择弹出框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="90%">
      <pat-visit-patient-select ref="patientSelectRef" :is-discharge-time="'1'" :org-id="queryParams.orgId"
                                @introduce="introduce"/>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!--   读卡弹窗-->
    <ReadCardVue
      ref="readCardRef"
      :card-data="cardData"
    />
  </div>
</template>
<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user.ts";
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {selectGroupByClassOnInp} from "@/api/hospitalization/inpBillDetail.ts"
import {addInpFeesMaster} from "@/api/inpFees/inpFeesMaster.ts"
import ReadCardVue from "@/views/msip/readCard/readCard.vue";
import readCardts, {MedicalCardData, ReadCardParams} from "@/api/msip/readCard.ts";
import {selectConfigByCache} from "@/api/system/orgConfig.ts";
import {ElMessage} from "element-plus";
import {ipDetailUpload, ipDetailUploadUndo, ipPreSettlement, ipSettlement} from "@/api/msip/ipSetl.ts";


const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "patient_medical_source",
    "medical_insurance_type",
    "sys_user_sex",
    "medical_read_card_type",
    "psn_setlway",
    "outp_settlement_business_type_dict",
    "insurance_type",
    "pat_prepayment_type",
    "pay_way_dict"
  )
);
const readCardRef = ref();
const apiDictType = ref(); //地区字典
const {idAuth} = readCardts();
const cardData = ref<MedicalCardData>();
const mdtrt_cert_type = ref();//就诊凭证类型
const mdtrt_cert_no = ref("");//就诊凭证编号
const patData = ref() //人员信息数据集
const preSetlData = ref();  //预结算数据集
const infoList = ref([]);// 人员参保信息
let dynamic_ip = ref(); //客户端电脑ip
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
// 患者是否医保信息，按钮禁用
const isNotMedical = ref(true);
const isPreSetl = ref(false);
const payWayListRef = ref();
const patientSelectRef = ref();
const patPrepaymentRef = ref();
const open = ref<boolean>(false);
const title = ref<string>("");
const {proxy} = getCurrentInstance() as any;
// 预交金列表
const patPrepaymentList = ref([])
// 收据费用列表
const inpBillDetailList = ref([])
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)

const queryParams = ref<any>({
  orgId: userInfo.orgId
})
// 应收总金额
const totalPrice = ref<number>(0.0);
//医保结算交易流水号
const ybSerialNo = ref<string>("");
//医保结算交易信息
const ybSerialData = ref<string>("");
// 找零
const retChange = ref<number>(0.0);
const inpOrOutp = ref<number>(2);
// 总计使用预交金总额
const prepaymentCosts = ref<number>(0.0);

const hospitalNoInputRef = ref(null);

// master.vue 新增方法
const focusHospitalNoInput = () => {
  nextTick(() => {
    hospitalNoInputRef.value?.focus();
  });
};

/**
 * 通过orgId key获取ApiDictType
 */
function selectApiDictType() {
  selectConfigByCache(userInfo.orgId, "api_dict_type").then((res => {
    apiDictType.value = res.data.configValue
  }));
}

// 暴露方法给父组件
defineExpose({
  focusHospitalNoInput
});

onMounted(() => {
  // 页面加载完成后，自动聚焦到住院号输入框
  focusHospitalNoInput();
  //获取医保地区自字典
  selectApiDictType();
});

/** 读卡 */
async function resetPatient(businesstype) {
  debugger
  if (!queryParams.value.medicalReadCardType) {
    return ElMessage.error("请选择读卡类型！");
  }
  mdtrt_cert_type.value = '0' + queryParams.value.medicalReadCardType;
  mdtrt_cert_no.value = queryParams.value.idNo;
  try {
    const params: ReadCardParams = {
      mdtrt_cert_type: mdtrt_cert_type.value, //就诊凭证类型: 01=医保电子凭证 02=居民身份证 03=社会保障卡 04=终端扫码 05=终端扫脸
      cardtype: "0",//卡片类型: 0=实体卡 1=电子社保卡 mdtrt_cert_type 为“03”时必填
      businesstype: businesstype, //用码业务类型: 01301=结算 mdtrt_cert_type 为“01”时必填
      operatorid: userInfo.userId, //收款员编号 mdtrt_cert_type 为“01”时必填
      operatorname: userInfo.userName, //收款员姓名 mdtrt_cert_type 为“01”时必填
      officeid: "",//医保科室编号 mdtrt_cert_type 为“01”时必填
      officename: "",//科室名称 mdtrt_cert_type 为“01”时必填
      name: queryParams.value.name,
      idNo: queryParams.value.idNo,
      org_id: userInfo.orgId, //机构id
      his_user_id: userInfo.userId, //用户id
    };
    const res = await idAuth(params, apiDictType.value, mdtrt_cert_no)
    debugger
    cardData.value = res;
    // 页面数据赋值
    patData.value = res;
    infoList.value = patData.value.insuinfo;
  } catch (err) {
    ElMessage.error('读卡失败，请检查终端连接');
  }
  // 使用for循环为参保类型赋值
  infoList.value.forEach((item, index) => {
    infoList.value[index] = item;
    if (item.psn_insu_stas == 1) {
      queryParams.value.canBaoType = item.insutype;
    }
  });
  nextTick(() => {
    readCardRef.value.show(); // 确保数据赋值后再显示弹窗
  });
}

// 医保费用明细上传
function detailUpload() {
  const param = {
    org_id: userInfo.orgId,//机构ID
    his_user_id: userInfo.userId,//用户id
    his_mdtrt_id: queryParams.value.visitId,//就诊id
  }
  ipDetailUpload(param).then((res: resType) => {
    if (res && res.code === 200) {
      ElMessage.success("费用上传成功！");
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    return ElMessage.error(err)
  });
}

// 医保费用明细上传
function detailUploadUndo() {
  const param = {
    org_id: userInfo.orgId,//机构ID
    his_user_id: userInfo.userId,//用户id
    his_mdtrt_id: queryParams.value.visitId,//就诊id
  }
  ipDetailUploadUndo(param).then((res: resType) => {
    if (res && res.code === 200) {
      ElMessage.success("费用撤销成功！");
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    return ElMessage.error(err)
  });
}

// 医保预结算
function medicalRegister() {
  if (!patData.value) {
    return ElMessage.error('请读卡进行身份认证！');
  }
  if (preSetlData.value) {
    return ElMessage.error('此患者已预结算！');
  }
  //患者身份校验
  let _psn_cert_type = patData.value.baseinfo.psn_cert_type;
  let _certno = patData.value.baseinfo.certno;
  let _psn_name = patData.value.baseinfo.psn_name;
  if (queryParams.value.idNo && _psn_cert_type == '01' && queryParams.value.idNo != _certno) {
    return ElMessage.error('患者【' + queryParams.value.name + '】与持卡人【' + _psn_name + '】身份证号不符，请核实！！！');
  }
  if (queryParams.value.name != _psn_name) {
    return ElMessage.error('患者【' + queryParams.value.name + '】与持卡人【' + _psn_name + '】姓名不符，请核实！！！');
  }
  // 组织参数
  let param = {
    his_mdtrt_id: queryParams.value.visitId,//HIS ID
    his_mdtrt_no: queryParams.value.hospitalNo,//HIS 住院号
    dynamic_ip: dynamic_ip.value,//动态ip
    his_user_id: userInfo.userId,//HIS 用户ID
    org_id: userInfo.orgId,//HIS 机构ID
    mdtrt_cert_type: mdtrt_cert_type.value,//就诊凭证类型
    mdtrt_cert_no: mdtrt_cert_no.value,//就诊凭证号
    acct_used_flag: queryParams.value.individualAccount ? '1' : '0',// 个人账户使用标志
    psn_setlway: queryParams.value.psnSetlway,//个人结算方式
    psn_no: patData.value.baseinfo.psn_no,//人员编号
    insutype: queryParams.value.canBaoType,//险种类型
    mid_setl_flag: '0',//中途结算标志
    dscgTime: queryParams.value.dischargeTime,//出院时间
  };
  ipPreSettlement(param).then((res: resType) => {
    if (res && res.code === 200) {
      preSetlData.value = res.data.output;
      // 校验费用
      let his_medfee_sumamt = totalPrice.value;
      if (his_medfee_sumamt != preSetlData.value.setlinfo.medfee_sumamt) {
        return ElMessage.error("HIS总费用【" + his_medfee_sumamt + "】与医保总费用【" + preSetlData.value.setlinfo.medfee_sumamt + "】不一致！请取消重新预结算！");
      }
      //组织支付方式
      setPays();
      isPreSetl.value = true;
      ElMessage.success("预结算成功");
    } else {
      return ElMessage.error(res.msg)
    }
  });
}

// 取消医保预结算
function medicalRegisterUndo() {
  preSetlData.value = null;
  isPreSetl.value = false;
  ElMessage.success("取消预结算成功");
}

/**
 * 预结算-支付方式赋值
 */
function setPays() {
  const setlinfo = preSetlData.value.setlinfo;
  let datas: any = [];

  // 固定金额部分
  const fixedAmounts = {
    fund: Number(setlinfo.fund_pay_sumamt || 0),
    hospital: Number(setlinfo.hosp_part_amt || 0),
    account: Number(setlinfo.acct_pay || 0),
    prepayment: Number(prepaymentCosts.value || 0)
  };

  // 计算固定部分总和
  const fixedTotal = Object.values(fixedAmounts).reduce((sum, val) => sum + val, 0);

  // 基金支付
  if (fixedAmounts.fund > 0) {
    datas.push({
      dictValue: '6',
      charges: fixedAmounts.fund.toFixed(2),
      sort: 1,
      disabled: true
    });
  }

  // 医院负担
  if (fixedAmounts.hospital > 0) {
    datas.push({
      dictValue: 'H01',
      charges: fixedAmounts.hospital.toFixed(2),
      sort: 2,
      disabled: true
    });
  }

  // 个人账户
  if (fixedAmounts.account > 0) {
    datas.push({
      dictValue: '3',
      charges: fixedAmounts.account.toFixed(2),
      sort: 3,
      disabled: true
    });
  }

  // 预交金
  if (fixedAmounts.prepayment > 0) {
    datas.push({
      dictValue: '99', // 使用99标识预交金
      charges: fixedAmounts.prepayment.toFixed(2),
      sort: 4,
      disabled: true
    });
  }

  // 计算个人现金（总金额 - 所有固定部分）
  const cashAmount = Number(totalPrice.value) - fixedTotal;

  // 仅当现金金额大于0时显示
  if (cashAmount != 0) {
    datas.push({
      dictValue: '5',
      charges: cashAmount.toFixed(2),
      sort: 5,
      disabled: false
    });
  }

  // 更新支付方式列表
  payWayListRef.value.tissuePayWayArray(datas);
}

/**费别点击事件 */
function chargeTypeChange(value: string) {
  if (value === "1") {
    isNotMedical.value = true;
    queryParams.value.ybSerialType = "4";
    queryParams.value.psnSetlway = "";
    queryParams.value.individualAccount = false;
  } else {
    isNotMedical.value = false;
    queryParams.value.ybSerialType = "11";
    queryParams.value.psnSetlway = "01";
    queryParams.value.individualAccount = true;
  }
}

function patientSelectClick() {
  open.value = true;
  nextTick(() => {
    const param = {
      chargeFlag: "1",
    };
    patientSelectRef.value.getParentList(param);
  });
}

// 支付方式input金额焦点消失事件
function payWayBlur(netReceiptsThis: number) {
  retChange.value = Number(netReceiptsThis);
}

/** 引用患者信息 */
function introduce(row: any) {
  debugger
  queryParams.value = row
  // 过滤出预交金列表中类型为 '1' 且 refundedId 为空的记录
  patPrepaymentList.value = row.patPrepaymentVos.filter((item: any) => item.type === '1' && item.refundedId == null)
  // 根据费用类型判断是否为医保患者，进而设置按钮禁用状态和个人账户支付状态
  if (queryParams.value.chargeType !== "1") {
    isNotMedical.value = false;
    queryParams.value.individualAccount = true;
    queryParams.value.psnSetlway = "01";
    queryParams.value.ybSerialType = "11";
  } else {
    isNotMedical.value = true;
    queryParams.value.individualAccount = false;
  }
  // 构建查询参数对象，用于查询结算列表数据
  const param = {
    visitId: queryParams.value.visitId,
    orgId: queryParams.value.orgId
  }
  selectGroupByClassOnInp(param).then((res: resType) => {
    // 将获取到的结算列表数据赋值给 inpBillDetailList
    inpBillDetailList.value = res.data
    let thisTotalPrice = 0 as number
    // 勾选预交金列表中的所有记录
    patPrepaymentList.value.forEach((item: any) => {
      patPrepaymentRef.value.toggleRowSelection(item, true);
    })
    // 循环结算列表，计算总金额
    inpBillDetailList.value.forEach((item: any) => {
      thisTotalPrice += Number(Number(item.charges).toFixed(2))
    })
    // 将计算得到的总金额保留两位小数后赋值给 totalPrice
    totalPrice.value = Number(thisTotalPrice.toFixed(2))
    // 在下次 DOM 更新循环结束之后执行延迟回调，清空支付方式列表并初始化支付方式选择
    nextTick(() => {
      payWayListRef.value.removePayWayAll()
      payWayListRef.value.initPayWayDictSelect()
      // 提取公共逻辑
      const shouldUsePrepaymentCosts = patPrepaymentList.value.length > 0 && prepaymentCosts.value > 0;
      const amountToSet = shouldUsePrepaymentCosts ? prepaymentCosts.value : totalPrice.value;
      // 空值检查
      if (payWayListRef.value) {
        payWayListRef.value.inpSetFirstPayWay(amountToSet);
      }
    })
  })
  cancel();
}

// 待收费患者选择弹出框
function cancel() {
  open.value = false;
}

/**
 * 结算确认
 */
function chargeOk() {
  if (!queryParams.value.visitId) {
    return ElMessage.error("请先选择需要收费的患者。");
  }
  let thisCountSum = 0.00

  if (!isNotMedical.value && !preSetlData.value) {
    return ElMessage.error('请先进行预结算！');
  }
  let payWayInfoList = payWayListRef.value.getPayWayDictList();
  let selfPayAmount = 0;
  payWayInfoList.forEach((payWay: any) => {
    payWay.moneyType = payWay.dictValue;
    payWay.orgId = queryParams.value.orgId;
    thisCountSum += Number(payWay.charges);
    if (!['6', 'H01', '3'].includes(payWay.dictValue)) {
      selfPayAmount += Number(payWay.charges) || 0;
    }
  });
  if (totalPrice.value != Number(thisCountSum.toFixed(2))) {
    return ElMessage.error(
      "实收金额和应收金额不相等，请检查结算信息是否正确，检查输入无误后再进行收费操作。"
    );
  }
  if (!isNotMedical.value) {
    const confirmMessage = selfPayAmount > 0
      ? `患者存在需要自费部分，金额为<span style="font-size: 50px; color: #ff4444">【¥${selfPayAmount}】</span>，请注意确认`
      : "患者无自费部分，是否直接医保结算？";
    ElMessageBox.confirm(confirmMessage, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true // 确保解析 HTML
    }).then(() => {
      //  组织参数
      let param = {
        mdtrt_id: preSetlData.value.setlinfo.mdtrt_id,
        his_mdtrt_id: queryParams.value.visitId,//HIS ID
        his_mdtrt_no: queryParams.value.hospitalNo,//HIS 住院号
        his_user_id: userInfo.userId,//HIS 用户ID
        org_id: userInfo.orgId,//HIS 机构ID
        med_type: queryParams.value.ybSerialType,//医疗类别
        mdtrt_cert_type: mdtrt_cert_type.value,//就诊凭证类型
        mdtrt_cert_no: mdtrt_cert_no.value,//就诊凭证号
        acct_used_flag: queryParams.value.individualAccount ? '1' : '0',// 个人账户使用标志
        mid_setl_flag: '0',//中途结算标志
        medfee_sumamt: totalPrice.value,//HIS总费用
        psn_setlway: queryParams.value.psnSetlway,//个人结算方式
        pays: payWayInfoList,
        psn_no: patData.value.baseinfo.psn_no,//人员编号
        insutype: queryParams.value.canBaoType,//险种类型
        dynamic_ip: dynamic_ip.value,//动态ip
        pre_setl_data: preSetlData.value,//预结算信息
        patPrepaymentBoList: ids.value, // 预交金ids
      };
      ipSettlement(param).then((res: resType) => {
        if (res && res.code === 200) {
          if (res.data.infcode === 2) {
            isPreSetl.value = true;
            againSetl(res.data.output);
          } else {
            nextTick(() => {
              payWayListRef.value.initPayWayDictSelect()
            })
            // 清空患者信息
            hospitalNoClear()
            isPreSetl.value = false;
            preSetlData.value = null;
            ElMessage.success("收费成功");
          }
        } else {
          return ElMessage.error(res.msg)
        }
      });
    });
  } else {
    ElMessageBox.confirm("确定要收费吗？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      let submitForm: any = {};
      submitForm.payWayInfoList = payWayInfoList;
      submitForm.payWayInfoList.forEach((item: any) => {
        item.paymentAmount = item.charges
      })
      submitForm.inpFeesMasterBo = {
        orgId: queryParams.value.orgId,
        visitId: queryParams.value.visitId,
        patientId: queryParams.value.patientId,
        ybSerialType: queryParams.value.ybSerialType,
        canBaoType: queryParams.value.canBaoType,
      };
      submitForm.patPrepaymentBoList = ids.value;
      submitForm.orgId = queryParams.value.orgId
      submitForm.totalPrice = totalPrice.value
      submitForm.ybSerialNo = ybSerialNo.value
      submitForm.ybSerialData = ybSerialData.value
      addInpFeesMaster(submitForm).then(() => {
        nextTick(() => {
          payWayListRef.value.initPayWayDictSelect()
        })
        // 清空患者信息
        hospitalNoClear()
        ElMessage.success("收费成功");
      });
    });
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.prepaymentId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
  let thisPrepaymentCosts = 0
  selection.forEach(item => {
    thisPrepaymentCosts += Number(item.amountOfMoney)
  })
  prepaymentCosts.value = Number(thisPrepaymentCosts.toFixed(2))
}

/**
 * 二次结算
 */
function againSetl(data) {
  ElMessageBox.confirm("此患者【预结算】报销金额与【正式结算】报销金额不符，是否继续结算？注：继续结算会将【正式结算】报销为准，请认真核对报销信息再次结算！！", {
    confirmButtonText: "继续",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    preSetlData.value = data;
    setPays();
  });
}

/**
 * 监控 总计使用预交金总额 事件
 */
watch(() => prepaymentCosts.value, (_newValue, _oldValue) => {
  payWayListRefInit()
})

/**
 * 处理支付方式金额
 */
function payWayListRefInit() {
  const thisPrepaymentCosts = Number(prepaymentCosts.value)
  nextTick(() => {
    if (patPrepaymentList.value.length > 0 && prepaymentCosts.value > 0) {
      // 添加第一行支付方式：预交金
      payWayListRef.value.inpSetFirstPayWay(prepaymentCosts.value, true)
    } else {
      if (payWayListRef.value) {
        payWayListRef.value.inpSetFirstPayWay(totalPrice.value)
      }
    }
  })
}

/**
 * 结算列表合计
 * @param param
 */
const getSummaries = (param: any) => {
  const {columns, data} = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      // sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
      sums[index] = h('div', {style: {'float': 'right', 'color': 'rgb(51, 91, 249)', 'font-size': '15px'}}, [
        '合计：',
      ])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `￥ ${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return (Number(prev) + Number(curr)).toFixed(2)
        } else {
          return (Number(prev)).toFixed(2)
        }
      }, 0)} 元`
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}

/**
 * 预交金列表合计
 * @param param
 */
const getPrepaymentSummaries = (param: any) => {
  const {columns, data} = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 5) {
      // sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
      sums[index] = h('div', {style: {'float': 'right', 'color': 'rgb(51, 91, 249)', 'font-size': '15px'}}, [
        '缴费金额总计：',
      ])
      return
    }
    if (index === 6) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `￥ ${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return (Number(prev) + Number(curr)).toFixed(2)
          } else {
            return (Number(prev)).toFixed(2)
          }
        }, 0)} 元`
      } else {
        sums[index] = 'N/A'
      }
    }
  })
  return sums
}

/**
 * 住院号清空事件
 */
function hospitalNoClear() {
  payWayListRef.value.removePayWayAll()
  payWayListRef.value.initPayWayDictSelect()
  queryParams.value = {
    chargeType: "1",
    orgId: userInfo.orgId
  }
  inpBillDetailList.value = []
  patPrepaymentList.value = []
  totalPrice.value = 0.00
  retChange.value = 0.00
  isNotMedical.value = true;
}
</script>

<style scoped>
/* 患者信息遮罩 */
.patient-info-container {
  position: relative;
}

.patient-mask {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

/* 费用信息遮罩 */
.fee-info-container {
  position: relative;
  height: 100%;
}

.fee-mask {
  width: 100%;
  height: calc(100% - 40px); /* 留出表格标题空间 */
  top: 10px;
  left: 0;
}

/* 预交金遮罩 */
.prepayment-container {
  position: relative;
  height: 100%;
}

.prepayment-mask {
  width: 100%;
  height: calc(100% - 40px); /* 留出表格标题和统计信息空间 */
  top: 10px;
  left: 0;
}

/* 公共遮罩样式 */
.mask-layer {
  position: absolute;
  background-color: rgb(12 176 199 / 15%);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.mask-content {
  text-align: center;
  color: #000000;
  font-size: 14px;
  padding: 14px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

:deep(.el-divider--horizontal) {
  margin: 10px 0 10px 0;
}

:deep(.el-form-item) {
  margin-bottom: 0px !important;
}

.search-container {
  padding: 0;
}

.pat-prepayment {
  position: absolute;
  bottom: 40px;
  margin-left: 20px;
  z-index: 99;
}

.span-font {
  font-size: 20px;
  font-weight: bold;
}

/* 调整患者信息整体布局 */
.patient-info-container {
  :deep(.el-form-item__label) {
    font-size: 13px !important;
    color: #333 !important;
  }

  :deep(.el-form-item__content) {
    font-size: 14px !important;
    color: #666 !important;
  }

  /* 特别设置第一行的顶部间距 */

  :deep(.el-row:first-child) {
    margin-top: 15px; /* 首行顶部间距 */
  }

  /* 调整表单项标签和内容的垂直间距 */

  :deep(.el-form-item) {
    margin-bottom: 4px; /* 表单项底部间距 */
    display: flex;
    align-items: center;
    height: 30px; /* 统一行高 */
  }

  /* 特别处理最后一行的底部间距 */

  :deep(.el-row:last-child) {
    margin-bottom: 15px; /* 最后一行底部留白 */
  }

  /* 保持输入框和按钮的垂直居中 */

  :deep(.el-input-group) {
    display: flex;
    align-items: center;
  }
}
</style>
